package com.opennews.openplatform.familyexpenseapi.controller

import com.opennews.openplatform.familyexpenseapi.config.AppConfigProperties
import com.opennews.openplatform.familyexpenseapi.service.AppReleaseLogService
import com.opennews.openplatform.myspringbootcore.dto.ApiResponse
import com.opennews.openplatform.myspringbootcore.util.getSuccessResponse
import org.springframework.core.env.Environment
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/app-release-log")
class AppReleaseLogController(
    private val appConfigProperties: AppConfigProperties,
    private val env: Environment,
    private val appReleaseLogService: AppReleaseLogService,
) {
    @GetMapping("/query-by-app-version")
    fun queryByAppVersion(@RequestParam appVersion: String): ResponseEntity<ApiResponse<Map<String, Any?>?>> {
        val result = appReleaseLogService.queryByAppVersion(appVersion)
        return getSuccessResponse(result)
    }

    @GetMapping("/query-latest-version")
    fun queryLatestVersion(@RequestParam appVersion: String): ResponseEntity<ApiResponse<Map<String, Any?>>> {
        val appInfo = appReleaseLogService.queryLatestVersion(appVersion)

        val result = mutableMapOf<String, Any?>().apply {
            put("hasUpdate", appInfo != null)

            // Map.of() Behavior
            // Immutable Map: Map.of() creates an immutable map where neither keys nor values can be null.
            // Throws Exception: If you attempt to pass null as either a key or a value, it throws a NullPointerException.
            // Because appInfo might be null. That's why Map.of() is NOT applicable here.
            put("appInfo", appInfo)

            put(
                "sharingH5Url",
                "${appConfigProperties.resource.httpBaseUrl}/${appConfigProperties.resource.h5DirectoryName}/app-sharing.html"
            )
        }

        return getSuccessResponse(result)
    }

    @GetMapping("/list-change-log")
    fun listChangeLog(
        @RequestParam pageSize: Int,
        @RequestParam pageIndex: Int,
    ): ResponseEntity<ApiResponse<List<Map<String, Any?>>>> {
        val result = appReleaseLogService.listChangeLog(pageSize, pageIndex)
        return getSuccessResponse(result)
    }
}